package com.xh.petdogexpert.sys.service.imp;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xh.petdogexpert.base.BaseException;
import com.xh.petdogexpert.base.ValudateForm;
import com.xh.petdogexpert.sys.dto.Resource;
import com.xh.petdogexpert.sys.dto.Role;
import com.xh.petdogexpert.sys.mapper.RoleMapper;
import com.xh.petdogexpert.sys.service.IResourceService;
import com.xh.petdogexpert.sys.service.IRoleService;
import com.xh.petdogexpert.user.dto.RoleResourceLink;
import com.xh.petdogexpert.user.mapper.RoleResourceLinkMapper;

@Transactional
@Service
public class RoleServiceImp implements IRoleService {

	@Autowired
	RoleMapper roleMapper;

	@Autowired
	RoleResourceLinkMapper roleResourceLinkMapper;

	@Autowired
	ValudateForm valudateForm;

	@Autowired
	IResourceService resourceService;;

	private Logger logger = LoggerFactory.getLogger(RoleServiceImp.class);

	@Override
	public List<Role> queryRoles(Role role) {

		List<Role> roles = roleMapper.queryRoles(role);

		return roles;
	}

	@Override
	public List<Role> getRoleResources(Role role) {
		return roleMapper.getRoleResources(role);

	}

	@Override
	public List<Resource> getRoleAllResources(Role role) throws BaseException {

		List<Resource> resources = resourceService.queryResources(new Resource());

		List<Role> nRoles = roleMapper.getRoleResources(role);

		if (nRoles.size() != 1) {
			throw new BaseException("获取role出错，不等于1个");
		}

		Role nRole = nRoles.get(0);

		List<Resource> roleResource = nRole.getResources();

		for (Resource i : roleResource) {
			for (Resource j : resources) {
				if (j.getId() == i.getId()) {
					j.setChecked(true);
				}
			}
		}

		return resourceService.makeTree(resources);
	}

	@Override
	public void updateRoleResources(List<RoleResourceLink> roleResourceLinks) {
		for(RoleResourceLink link : roleResourceLinks) {
			if(link.getResourceId() < 0) {
				link.setResourceId(-link.getResourceId());
				roleResourceLinkMapper.delete(link);
			} else{
				roleResourceLinkMapper.insert(link);
			}
		}
		
	}
}
